﻿using Furion.DistributedIDGenerator;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using net8.Helper;
using net8.Models;
using net8.Models.XiTong;
using net8.Views;
using net8.Views.XiTong;
using System.Data;

namespace net8.Controllers.XiTong
{
    /// <summary>
    /// 菜单管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class XtMenuController : ControllerBase
    {
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public List<MenuView> GetList()
        {
            string userId = User.Claims.First(u => u.Type == "UserId").Value;
            return RedisCacheHelper.GetMenuList(userId);
        }

        /// <summary>
        /// 获取菜单下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public List<TreeSelect> GetMenuSelect()
        {
            string userId = User.Claims.First(u => u.Type == "UserId").Value;
            return RedisCacheHelper.GetMenuSelect(userId);
        }

        /// <summary>
        /// 保存菜单
        /// </summary>
        /// <param name="model">菜单模型</param>
        [HttpPost]
        public void Save([FromBody] MenuView model)
        {
            DateTime current = DateTime.Now;
            XtMenu menu = new XtMenu()
            {
                Id = model.Id == Guid.Empty ? IDGen.NextID() : model.Id,
                AddTime = current,
                UpdateTime = current,
                IsDel = false,
                MenuName = model.MenuName,
                MenuPath = model.MenuPath,
                ParentId = model.ParentId,
                MenuIcon = model.MenuIcon,
                MenuOrder = model.MenuOrder
            };

            List<XtPermission> list = new List<XtPermission>();
            foreach (Guid item in model.RoleList)
            {
                list.Add(new XtPermission()
                {
                    Id = Guid.NewGuid(),
                    AddTime = current,
                    UpdateTime = current,
                    IsDel = false,
                    IsHalf = false,
                    MenuId = menu.Id,
                    RoleId = item
                });
            }

            var existList = DbHelper.Db.Queryable<XtPermission>().Where(p => p.MenuId == menu.Id).Select(p => new { p.Id, p.RoleId }).ToList();
            List<XtPermission> add = list.Where(p => !existList.Select(p => p.RoleId).Contains(p.RoleId)).ToList();
            List<Guid> del = existList.Where(p => !list.Select(p => p.RoleId).Contains(p.RoleId)).Select(p => p.Id).ToList();

            DbHelper.Db.Storageable(menu).ExecuteCommand();
            DbHelper.Db.Insertable(add).ExecuteCommand();
            if (del.Count > 0)
            {
                DbHelper.Db.Deleteable<XtPermission>().In(del).ExecuteCommand();
            }

            RedisCacheHelper.Init();
        }

        [HttpDelete]
        public void Delete(Guid id)
        {
            DbHelper.Db.Deleteable<XtMenu>().Where(m => m.Id == id).ExecuteCommand();
            RedisCacheHelper.Init();
        }

        /// <summary>
        /// 更新菜单序号
        /// </summary>
        /// <param name="model">菜单序号模型</param>
        [HttpPost]
        public void UpdateMenuOrder([FromBody] MenuOrder model)
        {
            List<XtMenu> list = DbHelper.Db.Queryable<XtMenu>().Where(m => m.ParentId == model.ParentId).OrderBy(m => m.MenuOrder).ToList();
            XtMenu current = list.First(m => m.Id == model.Id);
            int index = list.IndexOf(current);
            int newIndex = -1;
            if (model.IsUp && index == 0 || !model.IsUp && list.Count - 1 == index)
            {
                return;
            }
            if (model.IsUp && index > 0)
            {
                newIndex = index - 1;
            }
            else if (!model.IsUp && list.Count - 1 > index)
            {
                newIndex = index + 1;
            }
            XtMenu update = list[newIndex];
            update.MenuOrder = index + 1;
            current.MenuOrder = newIndex + 1;

            using var tran = DbHelper.Db.UseTran();
            DbHelper.Db.Updateable(current).ExecuteCommand();
            DbHelper.Db.Updateable(update).ExecuteCommand();
            tran.CommitTran();

            RedisCacheHelper.Init();
        }
    }

    public class MenuOrder
    {
        public Guid Id { get; set; }
        public Guid ParentId { get; set; }
        public bool IsUp { get; set; }
    }
}
